import type { Language } from 'element-plus/es/locale'
import type { ComponentSize } from 'element-plus'
import type { InjectionKey } from 'vue'
import { createStore, Store, useStore as baseUseStore } from 'vuex'

import zhCn from 'element-plus/dist/locale/zh-cn.mjs'

const language = {
  '简体中文': () => Promise.resolve(zhCn) as Promise<Language>,
  '繁体中文': () => import('element-plus/dist/locale/zh-tw.mjs') as Promise<Language>,
  'English': () => import('element-plus/dist/locale/en.mjs') as Promise<Language>,
}

// 为 store state 声明类型
export type RootState = {
  config: {
    /** 按钮设置：自动在两个中文字符之间插入空格 */
    autoInsertSpace: boolean;
    /** 可同时显示的消息最大数量 */
    maxMessageCount: number;
    /** 当前语言 */
    lanuage: keyof typeof language;
    /** 当前语言包 */
    locale: Language;
    /** 全局组件大小 */
    size: ComponentSize;
  }
}

// 定义 injection key
export const key: InjectionKey<Store<RootState>> = Symbol()

export const store = createStore<RootState>({
  state: {
    config: {
      maxMessageCount: 3,
      autoInsertSpace: false,
      lanuage: '简体中文',
      locale: zhCn,
      size: 'default'
    }
  },
  actions: {
    toggleLanguage: ({state}, lang: keyof typeof language) => {
      language[lang]().then(res => {
        state.config.locale = res
      })
    }
  },
  modules: {}
})

export function useStore () {
  return baseUseStore(key)
}
